package com.wang.study.commons;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {

//    private static SqlSessionFactory sqlSessionFactory;
//
//    private static ThreadLocal<SqlSession> t;
//
//    static {
//
//        if (t == null) {
//            System.out.println("================");
//            t=new ThreadLocal<SqlSession>();
//        }
//
//        //try  with  resources
//        try(InputStream is = Resources.getResourceAsStream("Mybatis-config.xml");){
//            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    public static <T>T getMapper(Class<T> clazz){
//        return getSqlSession().getMapper(clazz);
//    }
//
//    public static SqlSession getSqlSession(){
//        SqlSession sqlSession = t.get();
//
//        if (null == sqlSession) {
//            System.out.println("+++++++++++++++第一次");
//            sqlSession = sqlSessionFactory.openSession();
//            t.set(sqlSession);
//            return t.get();
//        }else{
//            return sqlSession;
//        }
//
//    }
//
//    public static void close(){
//        t.get().close();
//        t.remove();
//    }
private static SqlSession sqlSession;


    static {
        try {

            InputStream is = Resources.getResourceAsStream("Mybatis-config.xml");

            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);

            sqlSession=factory.openSession();


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //返回sqlSession对象方便手动提交事务
    public  static SqlSession getSqlSession(){
        return sqlSession;
    }
    public static <T>T getMapper(Class<T> clazz){

        return sqlSession.getMapper(clazz);
    }
}

